package com.livegoods.service;

import com.livegoods.mongodbdao.HouseDao4MongoDB;
import com.livegoods.pojo.House;
import com.livegoods.pojo.Order;
import com.livegoods.redisdao.HouseDao4Redis;
import com.livegoods.redisdao.HouseDao4RedisImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

@Service
public class BuyactionServiceImpl implements BuyactionService {


    @Autowired
    private HouseDao4Redis houseDao4Redis;

    @Autowired
    private HouseDao4MongoDB houseDao4MongoDB;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 预定房屋功能方法，做三件事
     *
     * 1， 修改redis中预定状态 isRented = true， Redis单线程（阻塞用户多用户操)
     * 2，修改MongoDB方法预定状态 isRented = true
     * 3，给当前用户下订单
     *
     *
     *
     * @param id 房屋id
     * @param user 用户
     * @return
     */
    @Override
    public boolean buyaction(String id, String user) {
        //重新组装key
        String key = "livegoods::"+id;

       try {
           //获取Redis中的缓存数据
           House house = houseDao4Redis.get(key);
           house.setRented(true);

           //调用redis的设置操作
           // 1， 修改redis中预定状态 isRented = true， Redis单线程（阻塞用户多用户操)
           boolean result = houseDao4Redis.set(key, house);

           if(result){
               //2，修改MongoDB方法预定状态 isRented = true
               long row = houseDao4MongoDB.update(id);
               if(row == 1){
                   //3，给当前用户下订单
                   Order order = new Order();
                   order.setImg(house.getImgs().get(0));
                   order.setPrice(house.getPrice());
                   order.setUser(user);
                   order.setTitle(house.getTitle());
                   order.setCommentState(0);
                   order.setHouseType(house.getInfo().get("type")+" - "+house.getHouseType()); //1室1厅1卫 - 48m²
                   order.setHouseId(house.getId());

                   order = mongoTemplate.save(order);

                   if(order.getHouseId()!=null){
                       return true;
                   }else {
                       return false;
                   }
               }
           }
       }catch (Exception e){
           e.printStackTrace();
           return false;
       }
       return false;
    }
}
